package com.mfy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfy.entity.User;
import com.mfy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author mfy
 * @since 2023-05-10
 */
@RestController
@RequestMapping
public class UserController {

    @Autowired
    private IUserService userService;

    //根据id查询用户对象
    @GetMapping("/selectOnebyId/{id}")
    public User selectOneById(@PathVariable int id) {
        return userService.getById(id);
    }

    //根据用户名模糊查询用户的集合
    @GetMapping("/selectByName/{name}")
    public List<User> selectByName(@PathVariable String name) {
        return userService.query().like("name", name).list();
    }

    @GetMapping("/users")
    public Map<String, Object> selectAllUser(
            @RequestParam(value = "page", required = false) Integer curPage,
            @RequestParam(value = "per_page", required = false) Integer pageSize,
            @RequestParam(value = "id", required = false) Integer userId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone) {
        IPage page = new Page(curPage, pageSize);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(userId)) {
            userQueryWrapper.eq("id", userId);
        }
        if (!StringUtils.isEmpty(name)) {
            userQueryWrapper.eq("name", name);
        }
        if (!StringUtils.isEmpty(phone)) {
            userQueryWrapper.eq("phone", phone);
        }
        IPage iPage = userService.page(page, userQueryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total_count", iPage.getTotal());
        map.put("items", iPage.getRecords());
        return map;
    }
}

